package com.apimanage.common.health;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * MySQL连接健康检查器
 * 检查MySQL数据库的连接状态
 *
 * @author API管理平台
 */
@Component
public class MySqlHealthChecker implements HealthChecker {
    
    private static final Logger logger = LoggerFactory.getLogger(MySqlHealthChecker.class);
    private static final String CHECKER_NAME = "MySQL数据库连接检查";
    private static final String TEST_QUERY = "SELECT 1";
    
    @Autowired
    private Environment environment;
    
    @Autowired(required = false)
    private DataSource dataSource;
    
    @Override
    public HealthCheckResult check() {
        HealthCheckResult result = new HealthCheckResult(true, CHECKER_NAME);
        
        Connection connection = null;
        Statement statement = null;
        
        try {
            if (dataSource != null) {
                // 使用已配置的数据源
                connection = dataSource.getConnection();
                statement = connection.createStatement();
                statement.executeQuery(TEST_QUERY);
                
                // 获取数据库信息
                String url = dataSource.getConnection().getMetaData().getURL();
                String username = environment.getProperty("spring.datasource.username");
                String driverClassName = environment.getProperty("spring.datasource.driver-class-name");
                
                result.addMessage("MySQL连接成功");
                result.addMessage("数据库URL: " + url);
                result.addMessage("用户名: " + (username != null ? username : "未配置"));
                result.addMessage("驱动类: " + (driverClassName != null ? driverClassName : "未配置"));
            } else {
                // 尝试从环境变量中获取配置并创建临时连接
                String url = environment.getProperty("spring.datasource.url");
                String username = environment.getProperty("spring.datasource.username");
                String password = environment.getProperty("spring.datasource.password");
                String driverClassName = environment.getProperty("spring.datasource.driver-class-name");
                
                if (url != null && username != null) {
                    DataSource tempDataSource = DataSourceBuilder.create()
                            .url(url)
                            .username(username)
                            .password(password)
                            .driverClassName(driverClassName)
                            .build();
                    
                    connection = tempDataSource.getConnection();
                    statement = connection.createStatement();
                    statement.executeQuery(TEST_QUERY);
                    
                    result.addMessage("MySQL连接成功 (临时连接)");
                    result.addMessage("数据库URL: " + url);
                    result.addMessage("用户名: " + username);
                } else {
                    result.setHealthy(false);
                    result.addMessage("未配置MySQL数据源");
                }
            }
        } catch (SQLException e) {
            result.setHealthy(false);
            result.addMessage("MySQL连接失败: " + e.getMessage());
            logger.error("MySQL连接检查失败", e);
        } catch (Exception e) {
            result.setHealthy(false);
            result.addMessage("MySQL健康检查异常: " + e.getMessage());
            logger.error("MySQL健康检查异常", e);
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                logger.error("关闭数据库连接时发生异常", e);
            }
        }
        
        return result;
    }
    
    @Override
    public String getName() {
        return CHECKER_NAME;
    }
}